package com.sy.controller;

import com.sy.common.bean.ResultBean;
import com.sy.common.controller.BaseController;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@Api(tags = "新增头像")
public class UploadController extends BaseController {
    private final String BASEDIR = "/attchment";//所有上传文件的根目录

    @PostMapping("/upload")
    public ResultBean upload(MultipartFile file, HttpServletRequest request) {
        String path = toUpload(file, request, null);
        return success("上传成功", path);
    }

    @PostMapping("/batch/upload")
    public ResultBean batchUpdate(List<MultipartFile> files, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        //批量上传
        files.forEach(file -> {
            if (!file.isEmpty()) {
                String tmp = toUpload(file, request, null);
                list.add(tmp);
            }
        });
        return success("上传成功", list);
    }

    /**
     * 上传单个文件
     *
     * @param file
     * @param request
     * @param type    目录  如果为空 默认为images
     * @return
     */
    String toUpload(MultipartFile file, HttpServletRequest request, String type) {
        //获取服务器上传的根目录
        FilePath filePath = initDir(request, type);
        String newFile = getNewFileName(file);
        //上传
        try {
            file.transferTo(new File(filePath.getRoot() + "\\" + newFile));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filePath.getDir()+"/" + newFile;
    }

    /**
     * 初始附件存储目录
     *
     * @param request
     * @return
     */
    FilePath initDir(HttpServletRequest request, String type) {
        if (null == type || "".equals(type))
            type = "images";

        //获取系统时间
        String relPath = BASEDIR + "/" + type + "/" + getSystemYMD();
        //获取服务器上传的根目录
        String root = request.getServletContext().getRealPath("/") + relPath;
        File dir = new File(root);
        if (!dir.exists())
            dir.mkdirs();//创建目录
        return new FilePath(dir.getAbsolutePath(), relPath);
    }

    class FilePath {
        String root;//根目录
        String dir;//相对目录

        public FilePath(String root, String dir) {
            this.root = root;
            this.dir = dir;
        }

        public String getRoot() {
            return root;
        }

        public void setRoot(String root) {
            this.root = root;
        }

        public String getDir() {
            return dir;
        }

        public void setDir(String dir) {
            this.dir = dir;
        }
    }


    /**
     * 20240404
     *
     * @return
     */
    String getSystemYMD() {
        LocalDate localDate = LocalDate.now();
        return localDate.format(DateTimeFormatter.ofPattern("yMMdd"));
    }

    /**
     * 获取新的文件名
     *
     * @param file
     * @return
     */
    String getNewFileName(MultipartFile file) {
        //获取原始文件名
        //获取上传文件的名称
        String name = file.getOriginalFilename();
        //获取文件的后缀
        String ext = name.substring(name.lastIndexOf(".")); //.jpg
        //新的文件名
        String newFile = UUID.randomUUID().toString() + ext;
        return newFile;
    }
}
